package com.example.foot;

import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvValidationException;
import org.apache.commons.math3.stat.correlation.PearsonsCorrelation;

import java.io.FileReader;
import java.io.IOException;
import java.util.*;

public class AgeGroupCounter {

    public static void main(String[] args) {
        // CSV文件路径
        String csvFile = "C:/Users/52739/Desktop/vue3数据可视化/vue3/Students Social Media Addiction.csv";
        // 统计年龄段的Map
        Map<Integer, Integer> ageGroupCount = new HashMap<>();
        int FemaleCount = 0;
        int MaleCount = 0;
        int graduateCount = 0;
        int undergraduateCount = 0;
        int highschoolCount = 0;
        int Two=0;
        int Three=0;
        int Four=0;
        int Five=0;
        int Six=0;
        int Seven=0;
        int Yes=0;
        int No=0;

        Map<String,Integer> countryCount = new HashMap<>();
        Map<String,Integer> SocialPlatformCount = new HashMap<>();
        Map<String,Integer> AddictionLevelCount = new HashMap<>();
        List<Double> YesUseTime = new ArrayList<>();
        List<Double> NoUseTime = new ArrayList<>();
        List<double[]> datalist = new ArrayList<>();
        Map<String, List<Double>> addictionToSocialAttackMap = new HashMap<>();


        try (CSVReader reader = new CSVReader(new FileReader(csvFile))) {
            // 跳过标题行
            reader.readNext();
            String[] line;

            // 读取CSV文件的每一行
            while ((line = reader.readNext()) != null) {
                int age = Integer.parseInt(line[1]); // 获取年龄列
                //统计性别
                if(line[2].equals("Female")) {
                    FemaleCount++;
                }else {
                    MaleCount++;
                }

                // 统计18到24岁之间的每个年龄
                if (age >= 18 && age <= 24) {
                    ageGroupCount.put(age, ageGroupCount.getOrDefault(age, 0) + 1);
                }
                //统计学历
                if(line[3].equals("Graduate")) {
                    graduateCount++;
                }else if(line[3].equals("Undergraduate")) {
                    undergraduateCount++;
                } else if (line[3].equals("High School")) {
                    highschoolCount++;
                }

                //国家集合
                String country=line[4];
                countryCount.put(country,countryCount.getOrDefault(country,0)+1);

                //最常用的社交平台
                String SocialPlatform=line[6];
                SocialPlatformCount.put(SocialPlatform,SocialPlatformCount.getOrDefault(SocialPlatform,0)+1);

                //每日使用时长
                double daliyUseTime= Double.parseDouble(line[5]);
                if (daliyUseTime >=2 && daliyUseTime <3) {
                    Two++;
                } else if (daliyUseTime >=3 && daliyUseTime <4) {
                    Three++;
                } else if (daliyUseTime >=4 && daliyUseTime <5) {
                    Four++;
                } else if (daliyUseTime >=5 && daliyUseTime <6) {
                    Five++;
                } else if (daliyUseTime >=6 && daliyUseTime <7) {
                    Six++;
                } else if (daliyUseTime >=7 && daliyUseTime <8) {
                    Seven++;
                }
                //对学业的影响
                String affected=line[7];
                if(affected.equals("Yes")) {
                   Yes++;
                   YesUseTime.add(daliyUseTime);
                }else {
                    No++;
                    NoUseTime.add(daliyUseTime);
                }
                //成瘾程度分布,上瘾
                String addiction=line[12];
                AddictionLevelCount.put(addiction,AddictionLevelCount.getOrDefault(addiction,0)+1);
                double socialAttackScore = Double.parseDouble(line[11]);
                String addictionScore=line[12];
                addictionToSocialAttackMap
                        .computeIfAbsent(addictionScore, k -> new ArrayList<>())
                        .add(socialAttackScore);
                //相关性热图
                double[] studentdata=new double[5];
                studentdata[0]=daliyUseTime;//平均每日使用时长
                studentdata[1]=Double.parseDouble(line[11]);//媒体冲突
                studentdata[2]=Double.parseDouble(line[8]);//每晚睡眠时长
                studentdata[3]=Double.parseDouble(line[9]);//心理健康分数
                studentdata[4]=Double.parseDouble(line[12]);//上瘾分数
                datalist.add(studentdata);

            }
            double[][] correlationMatrix = calculateCorrelationMatrix(datalist);

//             输出相关性矩阵
            printCorrelationMatrix(correlationMatrix);
//             打印每个年龄段的人数
            for (Map.Entry<Integer, Integer> entry : ageGroupCount.entrySet()) {
                System.out.println("年龄: " + entry.getKey() + ", 数量: " + entry.getValue());
            }

            System.out.println("女性: " + FemaleCount + ", 男性: " + MaleCount);
            System.out.println("高中: " + highschoolCount+ ", 本科: " + undergraduateCount+", 毕业: " + graduateCount);
            for (Map.Entry<String, Integer> entry : countryCount.entrySet()) {
                System.out.println("国家: " + entry.getKey() + ", 数量: " + entry.getValue());
            }
            for (Map.Entry<String, Integer> entry : SocialPlatformCount.entrySet()) {
                System.out.println("社交平台: " + entry.getKey() + ", 数量: " + entry.getValue());
            }
            System.out.println("2: " + Two + ", 3: " + Three+", 4: " + Four+", 5: " + Five+", 6: " + Six+", 7: " + Seven);
            System.out.println("Yes: " + Yes + ", No: " + No);
            System.out.println("MIN:" + Collections.min(YesUseTime));
            System.out.println("Q1:"+getPercentile(YesUseTime,25));
            System.out.println("Q2:"+getPercentile(YesUseTime,50));
            System.out.println("Q3:"+getPercentile(YesUseTime,75));
            System.out.println("MAX: " + Collections.max(YesUseTime));
            System.out.println("MIN:" + Collections.min(NoUseTime));
            System.out.println("Q1:"+getPercentile(NoUseTime,50));
            System.out.println("Q2:"+getPercentile(NoUseTime,75));
            System.out.println("Q3:"+getPercentile(NoUseTime,100));
            System.out.println("MAX: " + Collections.max(NoUseTime));
            for(Map.Entry<String, Integer> entry : AddictionLevelCount.entrySet()) {
                System.out.println("影响分数: " + entry.getKey() + ", 数量: " + entry.getValue());
            }
            // 计算并输出每个上瘾分数的社交攻击分数众数
            for (Map.Entry<String, List<Double>> entry : addictionToSocialAttackMap.entrySet()) {
                String addiction = entry.getKey();
                List<Double> socialAttackScores = entry.getValue();
                double mode = getMode(socialAttackScores);
                System.out.println("上瘾分数: " + addiction + ", 社会攻击众数: " + mode);
            }

        } catch (IOException | CsvValidationException e) {
            e.printStackTrace();
        }
    }

    private static double getPercentile(List<Double> data, int i) {
        int index = (int) Math.ceil(i / 100.0 * data.size()) - 1;
        return data.get(index);
    }

    // 计算皮尔逊相关系数矩阵
    public static double[][] calculateCorrelationMatrix(List<double[]> data) {
        int numColumns = data.get(0).length;
        double[][] correlationMatrix = new double[numColumns][numColumns];
        PearsonsCorrelation pearsonsCorrelation = new PearsonsCorrelation();

        // 计算每对列（特征）之间的相关性
        for (int i = 0; i < numColumns; i++) {
            for (int j = i; j < numColumns; j++) {
                double[] colI = new double[data.size()];
                double[] colJ = new double[data.size()];
                for (int k = 0; k < data.size(); k++) {
                    colI[k] = data.get(k)[i];
                    colJ[k] = data.get(k)[j];
                }
                double correlation = pearsonsCorrelation.correlation(colI, colJ);
                correlationMatrix[i][j] = correlation;
                correlationMatrix[j][i] = correlation; // 对称矩阵
            }
        }
        return correlationMatrix;
    }

    // 输出相关性矩阵
    public static void printCorrelationMatrix(double[][] correlationMatrix) {
        String[] labels = {"上瘾分数", "社交媒体冲突", "心理健康分数", "每晚睡眠时间", "平均每日使用时间"};
        for (int i = 0; i < correlationMatrix.length; i++) {
            for (int j = 0; j < correlationMatrix[i].length; j++) {
                System.out.printf("%-35s", labels[i] + " vs " + labels[j] + ": " + correlationMatrix[i][j]);
                System.out.println();
            }
        }
    }
    private static double getMode(List<Double> data) {
        Map<Double, Integer> frequencyMap = new HashMap<>();
        for (double value : data) {
            frequencyMap.put(value, frequencyMap.getOrDefault(value, 0) + 1);
        }

        double mode = data.get(0);
        int maxCount = 0;
        for (Map.Entry<Double, Integer> entry : frequencyMap.entrySet()) {
            if (entry.getValue() > maxCount) {
                mode = entry.getKey();
                maxCount = entry.getValue();
            }
        }
        return mode;
    }

}
